using System;
using System.IO;
using System.Xml.Serialization;
using CurrencyConv.Core.SettingsManager;

namespace CurrencyConv.Core.RatesDownloader
{
	public interface IContextPersister
	{
		void BackupOldRates();
		void SaveRates(CurrencyConvContext context);
		CurrencyConvContext LoadRates(out enumLoadRatesStatus status);
	}

	public enum enumLoadRatesStatus
	{
		FileNotFound,
		CouldNotReadFile,
		OK
	}

	public class ContextPersister : IContextPersister
	{
		public void BackupOldRates()
		{
			//TODO throw new NotImplementedException();
		}

		public void SaveRates(CurrencyConvContext context)
		{
			BackupOldRates();

			XmlSerializer serializer = new XmlSerializer(typeof(CurrencyConvContext));

			using (TextWriter writer = new StreamWriter(Consts.ExchangeRatesFilePath, false))
			{
				serializer.Serialize(writer, context);
			}
		}

		public CurrencyConvContext LoadRates(out enumLoadRatesStatus status)
		{
			XmlSerializer serializer = new XmlSerializer(typeof(CurrencyConvContext));

			if (!File.Exists(Consts.ExchangeRatesFilePath))
			{
				status = enumLoadRatesStatus.FileNotFound;
				return null;
			}

			CurrencyConvContext context;
			try
			{
				using (TextReader reader = new StreamReader(Consts.ExchangeRatesFilePath))
				{
					context = serializer.Deserialize(reader) as CurrencyConvContext;
				}
			}
			catch (Exception ex)
			{
				status = enumLoadRatesStatus.CouldNotReadFile;
				return null;
			}
			status = enumLoadRatesStatus.OK;
			return context;
		}
	}
}